import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/service/home.api.dart';
import 'package:rabbit_mobile/utils/powerset.dart';
import 'package:rabbit_mobile/view/goods_details/models/goods_details_model.dart';
import 'package:rabbit_mobile/widget/custom_cache_image_widget/index.dart';
import 'package:dotted_decoration/dotted_decoration.dart';

// ignore: library_private_types_in_public_api
GlobalKey<_GoodsDetailsOptionsState> goodsDetailsOptionsKey = GlobalKey(debugLabel: 'goodsDetailsOptionsKey');

enum specActionType {
  nomal,
  addCart,
  buyNow,
}

class GoodsDetailsOptions extends ConsumerStatefulWidget {
  final String imgUrl;
  final String price;
  final String oldPrice;
  final List<GoodsDetailsSpecs2Model> spec;
  final List<GoodsDetailsSkusModel> skus;
  final List<GoodsDetailsUserAddressModel> userAddresses;
  final void Function(String? showSpecStr)? showSpecsStrCallback;

  const GoodsDetailsOptions({
    super.key,
    required this.imgUrl,
    required this.oldPrice,
    required this.price,
    required this.spec,
    required this.skus,
    required this.userAddresses,
    this.showSpecsStrCallback,
  });

  @override
  _GoodsDetailsOptionsState createState() => _GoodsDetailsOptionsState();
}

class _GoodsDetailsOptionsState extends ConsumerState<GoodsDetailsOptions> {
  /// chahe size
  String size = '';

  /// goods specification
  String specification = '';

  /// goods number
  int goodsNum = 1;

  /// selected goods path sku
  List<String> cacheSpecSkusValues = [];
  Map pathmap = {};

  /// record specification path map
  Map<dynamic, dynamic> _specPathMap = {};

  /// selected sku, get new price and oldPrice
  List<GoodsDetailsSkusModel> _selectedGoodsSku = [];

  /// selected string
  String? _cacheSpecStr;

  /// determine address
  String? _determineAddress;

  /// goods skuId
  String? _goodsSkuId;

  /// 選中樣式
  final BoxDecoration _selectedBoxDecration = BoxDecoration(
    color: const Color.fromARGB(255, 234, 234, 234),
    borderRadius: BorderRadius.circular(25),
    border: Border.all(
      width: 1,
      color: const Color(0xFF00CE8A),
    ),
  );

  /// 默認樣式
  final BoxDecoration _defaultBoxDecration = BoxDecoration(
    color: const Color.fromARGB(255, 234, 234, 234),
    borderRadius: BorderRadius.circular(25),
    border: Border.all(
      width: 1,
      color: Colors.transparent,
    ),
  );

  /// 禁用狀態
  final DottedDecoration _disableDecration = DottedDecoration(
    color: Colors.grey,
    strokeWidth: .5,
    borderRadius: BorderRadius.circular(25),
  );

  /// 禁用字體顔色
  final Color _disableFontColor = Colors.grey;

  /// 選中字體顔色
  final Color _selectedFontColor = Color(0xFF00CE8A);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(goodsDetailsSpecsProvider.notifier).state = widget.spec;
    });
    _specPathMap = specGoodsSku(widget.skus);
    // 存儲
    cacheSpecSkusValues = List.filled(widget.spec.length, '', growable: true);
  }

  /// 定義匹配路徑
  void matchSpecsPathMap(List<GoodsDetailsSpecs2Model> spec, String name, int index) {
    // 獲取已選中的規格
    for (var i = 0; i < spec.length; i++) {
      GoodsDetailsSpecs2Model specsModel = spec[i];
      // 便利規格對應的值
      specsModel.values.forEach((GoodsDetailsSpecsValuesModel specValue) {
        if (i == index) {
          setState(() {
            cacheSpecSkusValues[index] = name;
          });
        }
      });
    }
    // 根據已選的組合生成規格路徑key
    for (var i = 0; i < spec.length; i++) {
      GoodsDetailsSpecs2Model specsModel = spec[i];
      specsModel.values.forEach((GoodsDetailsSpecsValuesModel specValue) {
        // 複製一份規格列表: 避免污染之前的規格數據造成數據混亂
        List cacheSpecSkusValuesTem = List.from(cacheSpecSkusValues);
        // 注意點: 已選擇的規格不需要組合
        if (cacheSpecSkusValuesTem.contains(specValue.name)) return;
        // 使用已選擇的規格進行組合
        cacheSpecSkusValuesTem[i] = specValue.name;
        cacheSpecSkusValuesTem.removeWhere((element) => element == '');
        // String selectedKey = cacheSpecSkusValuesTem.join('*');

        // 接下來就是匹配 cacheSpecSkusValues 有沒有 selectedKey, 如果沒有便更改 disable 的值, 再更新 UI 為不可選中的樣式

        // 匹配規格路徑字典
        // 這一步沒有成功, 因爲 riverpod 數據不可變沒有解決, 暫且擱置
      });
    }

    // 展示規格路徑狀態
    // 判斷規格是否選擇完成
    if (!cacheSpecSkusValues.contains('')) {
      String key = cacheSpecSkusValues.join('*');
      List<GoodsDetailsSkusModel>? goodsDetailsSkusList = _specPathMap[key] ?? [];
      _selectedGoodsSku = goodsDetailsSkusList!;
      if (goodsDetailsSkusList.isNotEmpty) {
        debugPrint('---${goodsDetailsSkusList[0].id}');
      } else {
        debugPrint('No matching SKU found for key: $key');
      }
    }

    if (cacheSpecSkusValues.join('') == '') {
      _selectedGoodsSku = [];
    }

    List cacheSpecSkusValuesTem = List.from(cacheSpecSkusValues);
    cacheSpecSkusValuesTem.where((element) => element == '');
    String cacheSpecStr = cacheSpecSkusValuesTem.join(' ');
    if (cacheSpecStr.isNotEmpty) {
      _cacheSpecStr = '已選: $cacheSpecStr';
    } else {
      _cacheSpecStr = null;
    }
  }

  /// 生成便利有庫存的路徑字典
  Map specGoodsSku(List<GoodsDetailsSkusModel> skus) {
    // 提取有庫存的skus規格
    // 遍歷 skus 庫存, 提取有庫存的skus
    for (var skus in skus) {
      // 存儲有數據的skus
      List skusSepc = [];
      if (skus.inventory > 0) {
        // 去除有庫存的skus, 放到列表中
        for (var specSkus in skus.specs) {
          skusSepc.add(specSkus.valueName);
        }
      }
      List<List> specSkusPower = powerset(skusSepc).toList();

      // 生成有庫存的規格路徑字典
      specSkusPower.forEach((List subSet) {
        if (subSet.length != 0) {
          // 將規格組合轉換成字典key: ['藍色', '10cm'] => '藍色*10cm'
          String key = subSet.join('*');
          if (!pathmap.containsKey(key)) {
            // 如果key不存在, 就建立新記錄
            pathmap[key] = [skus];
          } else {
            pathmap[key].add(skus);
          }
        }
      });
    }
    // 計算有庫存規格冪集
    return pathmap;
  }

  /// 彈窗
  Future showCupertinoModalPopups(specActionType type) {
    return showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (BuildContext context, setState) {
          return Stack(
            children: [
              Container(
                width: double.infinity,
                height: MediaQuery.of(context).size.height * 0.7,
                padding: const EdgeInsets.all(10),
                decoration: const BoxDecoration(
                  color: Colors.white,
                ),
                child: Stack(
                  children: [
                    Positioned(
                      top: -4,
                      right: -6,
                      child: IconButton(
                        onPressed: () {
                          Navigator.of(context, rootNavigator: true).pop();
                          widget.showSpecsStrCallback!('$specification $size');
                        },
                        icon: const Icon(Icons.close),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            CustomCacheImageWidget(
                              imageUrl: widget.imgUrl,
                              width: 90,
                              height: 90,
                            ),
                            const SizedBox(width: 10),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                RichText(
                                  text: TextSpan(
                                    text: '￥',
                                    style: const TextStyle(
                                      fontSize: 12,
                                      color: Color.fromRGBO(255, 0, 0, 1),
                                    ),
                                    children: [
                                      TextSpan(
                                        text: _selectedGoodsSku.isNotEmpty ? _selectedGoodsSku[0].price : widget.price,
                                        style: const TextStyle(
                                          fontSize: 16,
                                          color: Color.fromRGBO(255, 0, 0, 1),
                                        ),
                                      ),
                                      TextSpan(
                                        text: _selectedGoodsSku.isNotEmpty
                                            ? _selectedGoodsSku[0].oldPrice
                                            : widget.oldPrice,
                                        style: const TextStyle(
                                          decoration: TextDecoration.lineThrough,
                                          fontSize: 12,
                                          color: Colors.grey,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(
                                  width: MediaQuery.of(context).size.width * .7,
                                  child: Text(
                                    specification.isNotEmpty || size.isNotEmpty ? '已選:$specification $size' : "請選擇規格",
                                    style: const TextStyle(
                                      fontSize: 14,
                                      color: Colors.grey,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    maxLines: 1,
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                        ListView.separated(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: widget.spec.length,
                          itemBuilder: (BuildContext context, int index) {
                            final specItem = widget.spec[index];
                            return Container(
                              margin: const EdgeInsets.only(top: 20),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    specItem.name,
                                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                                  ),
                                  const SizedBox(height: 8),
                                  Wrap(
                                    spacing: 6,
                                    runSpacing: 4,
                                    children: List.generate(widget.skus[0].specs.length, (index2) {
                                      final GoodsDetailsSkusModel specValueItem = widget.skus[index2];
                                      return GestureDetector(
                                        onTap: () {
                                          _goodsSkuId = specValueItem.id;
                                          ref
                                              .read(goodsDetailsSpecsProvider.notifier)
                                              .updateGoodsDetailsSpec(specItem.name, specValueItem.specs[0].valueName);
                                          setState(() {
                                            if (index == 0) {
                                              if (specification == specValueItem.specs[0].name) {
                                                specification = '';
                                                for (var i = 0; i < cacheSpecSkusValues.length; i++) {
                                                  if (cacheSpecSkusValues[0] == specValueItem.specs[0].name) {
                                                    cacheSpecSkusValues[0] = '';
                                                    break;
                                                  }
                                                }
                                                return;
                                              }
                                              specification = specValueItem.specs[0].valueName;
                                            } else if (index == 1) {
                                              if (size == specValueItem.specs[0].name) {
                                                size = '';
                                                for (var i = 0; i < cacheSpecSkusValues.length; i++) {
                                                  if (cacheSpecSkusValues[1] == specValueItem.specs[0].name) {
                                                    cacheSpecSkusValues[1] = '';
                                                    break;
                                                  }
                                                }
                                                return;
                                              }
                                              size = specValueItem.specs[0].name;
                                            }
                                          });
                                          matchSpecsPathMap(widget.spec, specValueItem.specs[0].name, index);
                                        },
                                        child: Container(
                                          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
                                          decoration: specValueItem.specs[0].valueName == size ||
                                                  specValueItem.specs[0].valueName == specification
                                              ? _selectedBoxDecration
                                              : _defaultBoxDecration,
                                          child: Text(
                                            specValueItem.specs[index2].valueName,
                                            style: TextStyle(
                                              height: 1.0,
                                              color: specValueItem.specs[0].valueName == size ||
                                                      specValueItem.specs[0].valueName == specification
                                                  ? _selectedFontColor
                                                  : Colors.black,
                                            ),
                                          ),
                                        ),
                                      );
                                    }),
                                  ),
                                ],
                              ),
                            );
                          },
                          separatorBuilder: (BuildContext context, int index) {
                            return const SizedBox();
                          },
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              const Text(
                                "數量",
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                              Row(
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      if (goodsNum <= 1) return;
                                      setState(() {
                                        goodsNum--;
                                      });
                                    },
                                    child: const Icon(Icons.remove),
                                  ),
                                  Container(
                                    width: 50,
                                    height: 20,
                                    alignment: Alignment.center,
                                    decoration: const BoxDecoration(color: Color.fromARGB(255, 234, 234, 234)),
                                    child: Text('$goodsNum'),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      setState(
                                        () {
                                          goodsNum++;
                                        },
                                      );
                                    },
                                    child: const Icon(Icons.add),
                                  ),
                                ],
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Positioned(
                bottom: 6,
                left: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 50,
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Row(
                    children: [
                      if (type == specActionType.nomal)
                        Expanded(
                          child: Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: GestureDetector(
                                  onTap: () => actionOntap(specActionType.addCart),
                                  child: Container(
                                    height: 50,
                                    alignment: Alignment.center,
                                    decoration: const BoxDecoration(
                                        color: Colors.orange, borderRadius: BorderRadius.all(Radius.circular(25))),
                                    child: const Text(
                                      "加入購物車",
                                      style: TextStyle(fontSize: 18, color: Colors.white),
                                    ),
                                  ),
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                flex: 1,
                                child: GestureDetector(
                                  onTap: () => actionOntap(specActionType.buyNow),
                                  child: Container(
                                    height: 50,
                                    alignment: Alignment.center,
                                    decoration: const BoxDecoration(
                                        color: Colors.teal, borderRadius: BorderRadius.all(Radius.circular(25))),
                                    child: const Text(
                                      "立即購買",
                                      style: TextStyle(fontSize: 18, color: Colors.white),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      if (type == specActionType.addCart || type == specActionType.buyNow)
                        Expanded(
                          flex: 1,
                          child: GestureDetector(
                            onTap: () => actionOntap(type),
                            child: Container(
                              height: 50,
                              alignment: Alignment.center,
                              decoration: const BoxDecoration(
                                  color: Colors.teal, borderRadius: BorderRadius.all(Radius.circular(25))),
                              child: const Text(
                                "確定",
                                style: TextStyle(fontSize: 18, color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          );
        });
      },
    );
  }

  void actionOntap(specActionType type) async {
    // for (var i = 0; i < cacheSpecSkusValues.length; i++) {
    //   String spec = cacheSpecSkusValues[i];
    //   debugPrint(spec);
    //   if (spec == '') {
    //     EasyLoading.showToast('請選擇${widget.spec[i].name}');
    //   }
    // }
    if (specification.isEmpty) {
      EasyLoading.showToast("請選擇尺寸");
      return;
    } else if (size.isEmpty && widget.spec.length != 1) {
      EasyLoading.showToast('請選擇顔色');
      return;
    }
    switch (type) {
      case specActionType.addCart:
        try {
          await ShoppingCartApi.shoppingCartFetch({"count": goodsNum, "skuId": _goodsSkuId});
          await GetShoppingCartCountApi.getShoppingCartCountFetch();
          Navigator.of(context, rootNavigator: true).pop();
        } catch (e) {
          debugPrint('$e');
        }
        break;
      case specActionType.buyNow:
        debugPrint('立即購買');
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取 Riverpod 提供的规格项状态
    final List<GoodsDetailsSpecs2Model> specList = ref.watch(goodsDetailsSpecsProvider);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      width: double.infinity,
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(width: .6, color: Color.fromARGB(62, 158, 158, 158)),
        ),
      ),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              showCupertinoModalPopups(specActionType.nomal);
            },
            child: ListTile(
              dense: true,
              leading: const Text("已選"),
              title: Text(
                specification.isNotEmpty || size.isNotEmpty ? '已選:$specification $size' : "請選擇規格數量",
                style: const TextStyle(fontSize: 14, color: Colors.black),
              ),
              trailing: const Icon(
                Icons.chevron_right_outlined,
                color: Colors.grey,
              ),
            ),
          ),
          const Divider(height: 0, color: Color.fromARGB(62, 158, 158, 158)),
          GestureDetector(
            onTap: () {
              showCupertinoModalPopup(
                context: context,
                builder: (BuildContext context) {
                  return Stack(
                    children: [
                      Container(
                        padding: const EdgeInsets.only(top: 8),
                        width: double.infinity,
                        height: MediaQuery.of(context).size.height * 0.7,
                        color: Colors.white,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            const Text("配送至"),
                            Expanded(
                              child: ListView.separated(
                                shrinkWrap: true,
                                itemBuilder: (BuildContext, int index) {
                                  GoodsDetailsUserAddressModel GoodsDetailsUserAddressModelitem =
                                      widget.userAddresses[index];
                                  return InkWell(
                                    onTap: () {
                                      setState(() {
                                        _determineAddress = GoodsDetailsUserAddressModelitem.fullLocation;
                                      });
                                      Navigator.of(context, rootNavigator: true).pop();
                                    },
                                    child: ListTile(
                                      leading: const Icon(Icons.location_city_sharp),
                                      title: Row(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: <Widget>[
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Text(GoodsDetailsUserAddressModelitem.address),
                                              Text(GoodsDetailsUserAddressModelitem.fullLocation),
                                            ],
                                          ),
                                        ],
                                      ),
                                      trailing: Container(
                                        padding: EdgeInsets.symmetric(horizontal: 6.0, vertical: index == 0 ? 2.0 : .0),
                                        decoration: BoxDecoration(
                                          border: Border.all(
                                              width: index == 0 ? 1.0 : .0,
                                              color: index == 0 ? Colors.teal : Colors.transparent),
                                          borderRadius: const BorderRadius.all(
                                            Radius.circular(10),
                                          ),
                                          color: index == 0 ? Colors.teal : Colors.transparent,
                                        ),
                                        child: GoodsDetailsUserAddressModelitem.fullLocation != 0
                                            ? const Text(
                                                "默認",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                ),
                                              )
                                            : const SizedBox(),
                                      ),
                                    ),
                                  );
                                },
                                separatorBuilder: (BuildContext context, int index) {
                                  return Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 6.0),
                                    child: Container(
                                      height: 1,
                                      width: 10,
                                      decoration: BoxDecoration(
                                        color: Colors.grey.shade900,
                                      ),
                                    ),
                                  );
                                },
                                itemCount: widget.userAddresses.length,
                              ),
                            )
                          ],
                        ),
                      ),
                      const Positioned(
                        top: 8,
                        right: 8,
                        child: Icon(Icons.close),
                      ),
                      Positioned(
                        bottom: 12,
                        right: 0,
                        left: 0,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 24),
                          child: Container(
                            height: 40,
                            decoration: const BoxDecoration(
                              color: Colors.teal,
                              borderRadius: BorderRadius.all(Radius.circular(10)),
                            ),
                            child: const Center(
                              child: Text(
                                "添加地址",
                                style: TextStyle(color: Colors.white, fontSize: 16),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              );
            },
            child: ListTile(
              dense: true,
              leading: const Text("送至"),
              title: Text(
                _determineAddress ?? "暫無地址",
                style: const TextStyle(fontSize: 14, color: Colors.black),
              ),
              trailing: const Icon(
                Icons.chevron_right_outlined,
                color: Colors.grey,
              ),
            ),
          ),
          const Divider(height: 0, color: Color.fromARGB(62, 158, 158, 158)),
          const ListTile(
            dense: true,
            leading: Text("服務"),
            title: Text(
              "無憂退、貨快速退款、免費包郵",
              style: TextStyle(fontSize: 14, color: Colors.black),
            ),
            trailing: Icon(
              Icons.chevron_right_outlined,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }
}
